using Engine;
using Engine.Graphics;
using Game;

namespace SCIENEW {
    /// <summary>
    /// 只有四个朝向的机器
    /// </summary>
    public abstract class FourDirectionalDevice : DefaultDevice {
        public int FrontSlot, SideSlot, BackSlot, UpSlot, DownSlot;
        public bool Rotate;

        public FourDirectionalDevice(string id, int frontSlot, int backSlot = 107, int sideSlot = 107,  int upSlot = 107, int downSlot = 107, bool rotate = false) : base(id) {
            FrontSlot = frontSlot;
            SideSlot = sideSlot;
            BackSlot = backSlot;
            UpSlot = upSlot;
            DownSlot = downSlot;
            Rotate = rotate;
        }

        public override BlockPlacementData GetPlacementValue(SubsystemTerrain subsystemTerrain, ComponentMiner componentMiner, int value, TerrainRaycastResult raycastResult) {
            return new BlockPlacementData() { CellFace = raycastResult.CellFace, Value = DevicesBlockManager.GetDeviceValue(Id, DevicesUtils.GetDirectionXZ(componentMiner)) };
        }

        public override bool IsFaceTransparent(SubsystemTerrain subsystemTerrain, int face, int value) => false;

        public override int GetFaceTextureSlot(int face, int value) {
            if (face is 4) return UpSlot;
            if (face is 5) return DownSlot;
            if (face == GetDirection(value)) return FrontSlot;
            if (face == CellFace.OppositeFace(GetDirection(value))) return BackSlot;
            return SideSlot;
        }

        public override void GenerateTerrainVertices(BlockGeometryGenerator generator, TerrainGeometry geometry, int value, int x, int y, int z) {
            int direction = GetDirection(value);
            if (Rotate) {
                if (direction == 1 || direction == 3) {
                    generator.GenerateCubeVertices(BlocksManager.Blocks[BaseDeviceBlock.Index], value, x, y, z, 0, 1, 0, Color.White, geometry.GetGeometry(IndustrialModLoader.IETexture).OpaqueSubsetsByFace);
                    return;
                }
            }
            generator.GenerateCubeVertices(BlocksManager.Blocks[BaseDeviceBlock.Index], value, x, y, z, Color.White, geometry.GetGeometry(IndustrialModLoader.IETexture).OpaqueSubsetsByFace);
        }

        /// <summary>
        /// 获取方块朝向，默认直接以机器特殊值作为方块朝向
        /// 此方法会在判断方块面材质等地方调用
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected virtual int GetDirection(int value) => DevicesUtils.GetInnerData(value) & 0b11;
    }
}